package web;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {

    /**
     * 编码实现文件下载
     *      两个头，一个流
     *          content-type: 文件的mime类型
     *          content-disposition: 告诉浏览器以附件形式打开
     *
     *          需要下载的那个文件的输入流 - 知道文件路径
     *
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要下载资源名称
        String filename = req.getParameter("filename");

        ServletContext servletContext = getServletContext();
        //设置文件的mime类型
        String mimeType = servletContext.getMimeType(filename);
        resp.setHeader("content-type",mimeType);

        //设置以附件打开
        resp.setHeader("content-disposition","attachment;filename=" + filename);

        //读取要下载的文件,利用resp的输出流向浏览器端写出
        String path = servletContext.getRealPath("/" + filename);
        FileInputStream fis = new FileInputStream(path);
        ServletOutputStream os = resp.getOutputStream();

        //读写
        byte[] bys = new byte[1024];
        int len = -1;
        while ((len=fis.read(bys)) != -1){
            os.write(bys,0,len);
        }

        //释放资源
        fis.close();
    }
}
